/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */

/*
 * GuiRemoverLocacao.java
 *
 * Created on 27/11/2011, 19:57:38
 */

package GUI;

import java.util.Arrays;
import java.util.Vector;
import javax.swing.JOptionPane;
import javax.swing.table.DefaultTableModel;
import tp1POO.GestorLog;
import tp1POO.Modelo.Cliente;
import tp1POO.Modelo.Locacao;
import tp1POO.Modelo.ObjetoPOO;
import tp1POO.Modelo.Veiculo;
import tp1POO.Persistencia.GerenciadorObjetos;
import tp1POO.Persistencia.Pesquisa;
import tp1POO.Verifica;

/**
 *
 * @author matheus
 */
public class GuiRemoverLocacao extends javax.swing.JFrame {

	/** Creates new form GuiRemoverLocacao */
	public GuiRemoverLocacao() {
		initComponents();
		preencherJTable();
	}

	/** This method is called from within the constructor to
	 * initialize the form.
	 * WARNING: Do NOT modify this code. The content of this method is
	 * always regenerated by the Form Editor.
	 */
	@SuppressWarnings("unchecked")
    // <editor-fold defaultstate="collapsed" desc="Generated Code">//GEN-BEGIN:initComponents
    private void initComponents() {

        jPanel = new javax.swing.JPanel();
        jScrollPane1 = new javax.swing.JScrollPane();
        jTable = new javax.swing.JTable();
        jBFechar = new javax.swing.JButton();
        jBRemover = new javax.swing.JButton();

        setDefaultCloseOperation(javax.swing.WindowConstants.DO_NOTHING_ON_CLOSE);
        setTitle("Fechar Locação");

        jPanel.setBorder(javax.swing.BorderFactory.createTitledBorder(null, "Selecione uma Locação para ser removido", javax.swing.border.TitledBorder.DEFAULT_JUSTIFICATION, javax.swing.border.TitledBorder.DEFAULT_POSITION, new java.awt.Font("Dialog", 1, 14))); // NOI18N

        jTable.setModel(new javax.swing.table.DefaultTableModel(
            new Object [][] {

            },
            new String [] {
                "Cliente", "Marca", "Modelo", "Placa", "Data de Saída"
            }
        ) {
            boolean[] canEdit = new boolean [] {
                false, false, false, false, false
            };

            public boolean isCellEditable(int rowIndex, int columnIndex) {
                return canEdit [columnIndex];
            }
        });
        jScrollPane1.setViewportView(jTable);

        javax.swing.GroupLayout jPanelLayout = new javax.swing.GroupLayout(jPanel);
        jPanel.setLayout(jPanelLayout);
        jPanelLayout.setHorizontalGroup(
            jPanelLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(jPanelLayout.createSequentialGroup()
                .addComponent(jScrollPane1, javax.swing.GroupLayout.DEFAULT_SIZE, 521, Short.MAX_VALUE)
                .addContainerGap())
        );
        jPanelLayout.setVerticalGroup(
            jPanelLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(jPanelLayout.createSequentialGroup()
                .addComponent(jScrollPane1, javax.swing.GroupLayout.PREFERRED_SIZE, 160, javax.swing.GroupLayout.PREFERRED_SIZE)
                .addContainerGap(javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE))
        );

        jBFechar.setIcon(new javax.swing.ImageIcon(getClass().getResource("/Imagens/icoErro.gif"))); // NOI18N
        jBFechar.setText("Fechar");
        jBFechar.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                jBFecharActionPerformed(evt);
            }
        });

        jBRemover.setIcon(new javax.swing.ImageIcon(getClass().getResource("/Imagens/deletar.gif"))); // NOI18N
        jBRemover.setText("Remover");
        jBRemover.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                jBRemoverActionPerformed(evt);
            }
        });

        javax.swing.GroupLayout layout = new javax.swing.GroupLayout(getContentPane());
        getContentPane().setLayout(layout);
        layout.setHorizontalGroup(
            layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(javax.swing.GroupLayout.Alignment.TRAILING, layout.createSequentialGroup()
                .addContainerGap()
                .addComponent(jPanel, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                    .addComponent(jBRemover)
                    .addComponent(jBFechar))
                .addContainerGap())
        );

        layout.linkSize(javax.swing.SwingConstants.HORIZONTAL, new java.awt.Component[] {jBFechar, jBRemover});

        layout.setVerticalGroup(
            layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(layout.createSequentialGroup()
                .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                    .addGroup(layout.createSequentialGroup()
                        .addGap(48, 48, 48)
                        .addComponent(jBRemover)
                        .addGap(39, 39, 39)
                        .addComponent(jBFechar))
                    .addGroup(layout.createSequentialGroup()
                        .addContainerGap()
                        .addComponent(jPanel, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)))
                .addContainerGap(javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE))
        );

        layout.linkSize(javax.swing.SwingConstants.VERTICAL, new java.awt.Component[] {jBFechar, jBRemover});

        pack();
    }// </editor-fold>//GEN-END:initComponents


	private void preencherJTable(){
		DefaultTableModel modelo = (DefaultTableModel)jTable.getModel();
		modelo.setNumRows(0);
		Locacao objeto;

		Vector<Locacao> obj = Pesquisa.locacoesEmAberto();

		for (int i=0;i<obj.size();i++){
			objeto = (Locacao) obj.get(i);
			modelo.addRow(new Object[] {objeto.getLocador().getNome(),objeto.getVeiculo().getMarca(),objeto.getVeiculo().getModelo(),objeto.getVeiculo().getPlaca(),objeto.getDataSaida()});
		}
	}















	private void jBFecharActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_jBFecharActionPerformed
		GestorLog.obterInstancia().inserirMsgLog("Funcionalidade de Remover locação foi fechada("+GuiCreator.obterInstancia().getGuiFuncionalidades().getFuncionario().getCpf()+")");
		GuiCreator.obterInstancia().removerGuiRemLoc();
	}//GEN-LAST:event_jBFecharActionPerformed

	private void jBRemoverActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_jBRemoverActionPerformed
		DefaultTableModel modelo = (DefaultTableModel)jTable.getModel();
		int linha = jTable.getSelectedRow();

		if (jTable.getSelectedRow()>=0){

			String nome = (String) jTable.getValueAt(linha, 0);
			String placa = (String)jTable.getValueAt(linha, 3);
			String data = (String)jTable.getValueAt(linha, 4);

			Locacao obj = Pesquisa.ObterLocacao(nome, placa, data);

			if (obj != null) {
				String opcao = JOptionPane.showInputDialog(jPanel, "Insira Km de entrada : ", "Cadastrar Motorista", JOptionPane.QUESTION_MESSAGE);
				if (opcao==null) {

				}
				else if (opcao.isEmpty()) {
					JOptionPane.showMessageDialog(jTable,"ERRO : Km de entrada Inválido!", "Error", JOptionPane.ERROR_MESSAGE);
				}
				else {
					obj.setKmEntrada(Integer.parseInt(opcao));
                                        Vector<ObjetoPOO> motTemp = new Vector<ObjetoPOO>(Arrays.asList(obj.getMotoristas().toArray(new ObjetoPOO[0])));
					if (obj.fecharLocacao())
                                        {
						Verifica.dependenciaLocacao(obj);
                                                GerenciadorObjetos.obterInstancia().salvarObjs(motTemp.toArray(new ObjetoPOO[0]));
                                        }
					modelo.removeRow(linha);
					GestorLog.obterInstancia().inserirMsgLog(GuiCreator.obterInstancia().getGuiFuncionalidades().getFuncionario().getCpf()+
							" - Locacção removido com sucesso!\n\tCliente : "+obj.getLocador().getNome()+
							"\n\tVeículo : "+obj.getVeiculo().getMarca()+", "+obj.getVeiculo().getModelo()+
							"\n\tData de Saída : "+obj.getDataSaida());
					JOptionPane.showMessageDialog(jPanel,"Locação removido com Sucesso!", "Sucesso", JOptionPane.INFORMATION_MESSAGE);
				}
			}
		} else{
			JOptionPane.showMessageDialog(jTable,"ERRO : Nenhuma locação foi selecionada!", "Error", JOptionPane.ERROR_MESSAGE);
		}
	}//GEN-LAST:event_jBRemoverActionPerformed















	/**
	 * @param args the command line arguments
	 */
	public static void main(String args[]) {
		java.awt.EventQueue.invokeLater(new Runnable() {
			public void run() {
				new GuiRemoverLocacao().setVisible(true);
			}
		});
	}

    // Variables declaration - do not modify//GEN-BEGIN:variables
    private javax.swing.JButton jBFechar;
    private javax.swing.JButton jBRemover;
    private javax.swing.JPanel jPanel;
    private javax.swing.JScrollPane jScrollPane1;
    private javax.swing.JTable jTable;
    // End of variables declaration//GEN-END:variables

}
